
package com.javaleague.sesionUsuario;

import java.io.IOException;
import java.io.PrintWriter;
import com.javaleague.Constantes;
import com.javaleague.informacion.InformacionGeneral;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.javaleague.persistencia.DAOUpdateEmail;

/**
 * @author TaixMiguel
 */
public class UpdateEmail extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        HttpSession session = request.getSession(true);
        Usuario user = (Usuario)session.getAttribute("usuario");
        
        if (user != null) {
            if (request.getParameter("oldEmail") != null) {
                String oldEmail = request.getParameter("oldEmail");
                String newEmail = request.getParameter("newEmail");
        
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();

                if (DAOUpdateEmail.actualizarEmail(user.getId(), user.getTokenUser(), oldEmail, newEmail, user.getNombre(), request.getRemoteAddr())) {
                    user.setMail(newEmail);
                    session.setAttribute( "usuario", user);
                    response.sendError(200);
                } else
                    response.sendError(603);

                out.close();
            } else {
                InformacionGeneral.guardarLog(Object.class.getName(), Constantes.Informacion.InfoMensajes.IntentoActualizadoEmailUsuario, user.getNombre(), request.getRemoteAddr());
                response.sendError(403);
            }
        } else {
            InformacionGeneral.guardarLog(Object.class.getName(), Constantes.Informacion.InfoMensajes.IntentoActualizadoEmailUsuario, "Anonimus", request.getRemoteAddr());
            response.sendError(403);
        }
    }
    
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}